/* eslint-disable */
import React, { useState, useEffect, useRef } from "react";
import {
  sendCompanionMessage,
  getCompanionProfile,
  createCompanionProfile,
  checkSensitiveWords,
  
} from "./botaxios";
// 导入敏感词JSON数据
import sensitiveWordsData from "./sensitiveWords.json";
// 导入Stability AI图片生成功能

import type { SensitiveCheckResult } from "./botaxios";
// import type { KeyboardEvent } from "react";
import { useNavigate } from "react-router-dom";
import { Spin, Button, Avatar } from "antd";
import {
  ArrowLeftOutlined,
  SendOutlined,
  StarOutlined,
  SmileOutlined,
  PictureOutlined,
} from "@ant-design/icons";
import "./CompanionProfile.css";
import CompanionProfile from "./CompanionProfile";
import img1 from "./images/pic.png";
import img2 from "./images/pic1.png";

// 用户头像
const USER_AVATARS = [
  "https://api.dicebear.com/8.x/bottts/svg?seed=user1",
  "https://api.dicebear.com/8.x/bottts/svg?seed=user2",
  "https://api.dicebear.com/8.x/bottts/svg?seed=user3",
];

// 消息类型
type MessageType = {
  role: "user" | "companion";
  content: string;
  imageUrl?: string;
};

// 语音风格映射
const STYLE_TO_VOICE: Record<string, string> = {
  温柔型: "x4_xiaoyan",
  撒娇型: "aisbabyxu",
  高冷御姐型: "x4_lingxiaoyun_talk_emo",
  可爱型: "x2_qianxun",
  日常型: "xiaoqi",
};

// 头像图片
const COMPANION_AVATARS = [img1, img2];

// 在顶部添加风格类型常量
const STYLE_TYPES = [
  "温柔型",
  "撒娇型", 
  "高冷御姐型",
  "可爱型",
  "日常型"
];

// 风格对应的描述
const STYLE_TYPE_DESCRIPTIONS: Record<string, string> = {
  "温柔型": "温柔体贴，善解人意，情绪稳定，擅长安慰和包容",
  "撒娇型": "活泼可爱，喜欢撒娇，经常使用亲昵的称呼和表情",
  "高冷御姐型": "成熟稳重，略带距离感，言简意赅，偶尔流露温柔",
  "可爱型": "天真烂漫，充满童趣，活泼开朗，喜欢卖萌",
  "日常型": "自然随和，生活化，像真实情侣一样互动交流"
};

// 在组件顶部添加CSS样式
const styleDropdownStyle: React.CSSProperties = {
  backgroundColor: 'rgba(255, 192, 203, 0.1)',
  borderRadius: '15px',
  border: '1px solid rgba(255, 150, 180, 0.3)',
  padding: '2px 10px',
  fontSize: '12px',
  color: '#ff5b99',
  cursor: 'pointer',
  appearance: 'none',
  backgroundImage: 'url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23ff5b99%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E")',
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'right 0.7em top 50%',
  backgroundSize: '0.65em auto',
  paddingRight: '20px'
};

// 自定义下拉框组件
const StyleDropdown: React.FC<{
  value: string;
  options: string[];
  onChange: (value: string) => void;
}> = ({ value, options, onChange }) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <div 
      className={`style-dropdown ${isOpen ? 'style-dropdown-open' : ''}`}
      ref={dropdownRef}
    >
      <div 
        className="style-dropdown-selected"
        onClick={() => setIsOpen(!isOpen)}
      >
        {value}
      </div>
      <div className="style-dropdown-menu">
        {options.map(option => (
          <div 
            key={option}
            className={`style-dropdown-item ${option === value ? 'active' : ''}`}
            onClick={() => {
              onChange(option);
              setIsOpen(false);
            }}
          >
            {option}
          </div>
        ))}
      </div>
    </div>
  );
};

const ChatBot: React.FC = () => {
  const navigate = useNavigate();
  const [messages, setMessages] = useState<MessageType[]>([
    {
      role: "companion",
      content: "你好呀！我是小悠，很高兴认识你~今天想聊些什么呢？",
    },
  ]);
  const [input, setInput] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [styleType, setStyleType] = useState<string>("撒娇型");
  const [profileReady, setProfileReady] = useState(false);
  const [companionMood, setCompanionMood] = useState<number>(45);
  const [companionAvatar, setCompanionAvatar] = useState<string>("");
  const [userAvatar, setUserAvatar] = useState<string>("");
  const [showProfile, setShowProfile] = useState(false);

  const [outfitLoading, setOutfitLoading] = useState(false);
  const chatEndRef = useRef<HTMLDivElement | null>(null);
  const messageListRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 添加生气状态相关变量
  const [isAngry, setIsAngry] = useState<boolean>(false);
  const [angerTimer, setAngerTimer] = useState<any>(null);
  const [angerMessage, setAngerMessage] = useState<string>(
    "你的话伤害了她的感情，请不要再说这样的话..."
  );
  const [shouldExit, setShouldExit] = useState<boolean>(false);
  const [angerEmoji, setAngerEmoji] = useState<string>(
    "https://imgs.aixiaocai.com/assets/xiaoyou/angry_emoji.png"
  );
  const [isLoadingEmoji, setIsLoadingEmoji] = useState<boolean>(false);

  // 添加亲密互动相关状态和函数
  const [showQuickActions, setShowQuickActions] = useState<boolean>(false);

  // 亲密互动选项
  const INTIMATE_ACTIONS = [
    { icon: "💋", text: "想亲亲你" },
    { icon: "🤗", text: "想抱抱你" },
    { icon: "💕", text: "爱你哦" },
    { icon: "👫", text: "想牵你的手" },
    { icon: "😘", text: "好想你" },
  ];

  // 表情和图片上传相关状态
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 常用表情列表
  const commonEmojis = [
    "😊",
    "😍",
    "🥰",
    "😘",
    "😂",
    "❤️",
    "👋",
    "👍",
    "🌹",
    "✨",
    "💋",
    "🤗",
    "💕",
    "👫",
  ];

  // 添加敏感词退出计时器
  const [exitTimer, setExitTimer] = useState<NodeJS.Timeout | null>(null);

  // 在组件顶部附近，添加一个新状态
  const [generatingImage, setGeneratingImage] = useState<boolean>(false);

  // 添加穿搭图片发送日期记录
  const [lastOutfitDate, setLastOutfitDate] = useState<string>("");

  // 在组件顶部添加预览图片相关状态
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [showImagePreview, setShowImagePreview] = useState<boolean>(false);

  // 在组件内添加亲密度状态
  const [intimacy, setIntimacy] = useState<number>(0);

  // 在组件初始化时加载亲密度
  useEffect(() => {
    // 从本地存储加载亲密度
    const savedIntimacy = localStorage.getItem('companion_intimacy');
    if (savedIntimacy) {
      setIntimacy(parseInt(savedIntimacy, 10));
    }
  }, []);

  // 更新亲密度的函数
  const updateIntimacy = (increment: number) => {
    const newIntimacy = Math.min(100, intimacy + increment);
    setIntimacy(newIntimacy);
    localStorage.setItem('companion_intimacy', newIntimacy.toString());
  };

  // 处理风格变更
  const handleStyleChange = (style: string) => {
    setStyleType(style);
    // 可以在这里加入更多逻辑，比如通知服务器风格变更等
    console.log(`风格已更改为: ${style}`);
  };

  // 处理亲密互动点击
  const handleIntimateAction = (text: string) => {
    setInput(text);
    // 聚焦输入框
    inputRef.current?.focus();
    // 隐藏快捷操作菜单
    setShowQuickActions(false);
  };

  // 切换显示快捷操作菜单
  const toggleQuickActions = () => {
    setShowQuickActions((prev) => !prev);
  };

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };

  // 处理点击小悠头像查看详情
  const handleAvatarClick = () => {
    setShowProfile(true);
  };

  // 只在挂载时获取/创建 profile
  useEffect(() => {
    // Initialize mood and avatars
    setCompanionMood(Math.floor(Math.random() * 40) + 30); // 30-70范围的心情值
    setCompanionAvatar(COMPANION_AVATARS[1]); // 使用固定头像
    setUserAvatar(
      USER_AVATARS[Math.floor(Math.random() * USER_AVATARS.length)]
    );

    (async () => {
      try {
        await getCompanionProfile();
        setProfileReady(true);

        // 首次加载页面时自动获取今日穿搭
     
      } catch {
        await createCompanionProfile({
          name: "小悠",
          personality: "温柔",
          interests: ["音乐", "旅行"],
          background: "AI伴侣",
          style_type: styleType,
        });
        setProfileReady(true);

  
    
      }
    })();
  }, []);





  // 添加本地敏感词检测函数
  const checkSensitiveWordsLocally = (text: string): SensitiveCheckResult => {
    const lowercaseText = text.toLowerCase();
    
    // 检查高级别敏感词
    const highLevelWords = sensitiveWordsData.sensitiveWords.high || [];
    const matchedHigh = highLevelWords.filter((word) =>
      lowercaseText.includes(word)
    );
    if (matchedHigh.length > 0) {
      console.log("检测到高级别敏感词:", matchedHigh);
      return {
        is_sensitive: true,
        matched_words: matchedHigh,
        sensitivity_level: "high",
        suggested_response: sensitiveWordsData.reactions.high.response,
        mood_change: sensitiveWordsData.reactions.high.mood_change,
        should_exit: sensitiveWordsData.reactions.high.should_exit,
      };
    }
    
    // 检查中级别敏感词
    const mediumLevelWords = sensitiveWordsData.sensitiveWords.medium || [];
    const matchedMedium = mediumLevelWords.filter((word) =>
      lowercaseText.includes(word)
    );
    if (matchedMedium.length > 0) {
      console.log("检测到中级别敏感词:", matchedMedium);
      return {
        is_sensitive: true,
        matched_words: matchedMedium,
        sensitivity_level: "medium",
        suggested_response: sensitiveWordsData.reactions.medium.response,
        mood_change: sensitiveWordsData.reactions.medium.mood_change,
        should_exit: sensitiveWordsData.reactions.medium.should_exit,
      };
    }
    
    // 检查低级别敏感词
    const lowLevelWords = sensitiveWordsData.sensitiveWords.low || [];
    const matchedLow = lowLevelWords.filter((word) =>
      lowercaseText.includes(word)
    );
    if (matchedLow.length > 0) {
      console.log("检测到低级别敏感词:", matchedLow);
      return {
        is_sensitive: true,
        matched_words: matchedLow,
        sensitivity_level: "low",
        suggested_response: sensitiveWordsData.reactions.low.response,
        mood_change: sensitiveWordsData.reactions.low.mood_change,
        should_exit: sensitiveWordsData.reactions.low.should_exit,
      };
    }
    
    // 没有匹配任何敏感词
    return {
      is_sensitive: false,
      matched_words: [],
      sensitivity_level: null,
      suggested_response: null,
      mood_change: 0,
      should_exit: false,
    };
  };

  // 处理发送消息
  const handleSend = async () => {
    if (!input.trim() || loading) return;

    // 添加用户消息到列表
    const userMessage: MessageType = {
      role: "user",
      content: input,
    };
    setMessages((prev) => [...prev, userMessage]);
    setInput("");
    setLoading(true);

    try {
      // 先本地检查是否包含敏感词
      const localSensitiveCheck = checkSensitiveWordsLocally(input);
      
      if (localSensitiveCheck.is_sensitive) {
        // 如果本地检测到敏感词，直接处理
        await handleSensitiveWordDetection(localSensitiveCheck);
        return;
      }
      
      // 如果本地没检测到，尝试通过API检查
      try {
        const sensitiveResult = await checkSensitiveWords(input);
        if (sensitiveResult.is_sensitive) {
          await handleSensitiveWordDetection(sensitiveResult);
          return;
        }
      } catch (error) {
        console.error("敏感词API检测失败，使用本地结果", error);
        // API失败，使用本地检测结果
        if (localSensitiveCheck.is_sensitive) {
          await handleSensitiveWordDetection(localSensitiveCheck);
          return;
        }
      }

      // 如果没有敏感词，正常发送消息
      const response = await sendCompanionMessage(input, styleType);
      
      if (response && response.content) {
        const companionMessage: MessageType = {
          role: "companion",
          content: response.content,
          imageUrl: response.imageUrl === null ? undefined : response.imageUrl,
        };
        
        // 更新消息列表
        setMessages((prev) => [...prev, companionMessage]);
        
        // 更新心情值
        if (response.mood !== undefined) {
          setCompanionMood(response.mood);
        }
        
        // 增加亲密度
        updateIntimacy(1);
      }
    } catch (error) {
      console.error("发送消息失败", error);
      setMessages((prev) => [
        ...prev,
        {
          role: "companion",
          content: "抱歉，我现在无法回复你的消息，请稍后再试。",
        },
      ]);
    } finally {
      setLoading(false);
      // 滚动到底部
      setTimeout(() => {
        chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
      }, 100);
    }
  };

  // 处理敏感词检测
  const handleSensitiveWordDetection = async (result: SensitiveCheckResult) => {
    // 降低心情值
    setCompanionMood((prev) => Math.max(0, prev + result.mood_change));

    // 如果是高度敏感词，设置3秒后强制退出
    if (result.sensitivity_level === "high") {
      setIsAngry(true);
      setAngerMessage("你的话让小悠非常难过，将在3秒后退出...");
      
      // 清除之前的计时器
      if (exitTimer) {
        clearTimeout(exitTimer);
      }
      
      // 设置3秒后退出的计时器
      const timer = setTimeout(() => {
        // 退出到上一页
        navigate(-1);
      }, 3000);
      
      setExitTimer(timer);
      setLoading(false);
      return;
    }
    
    // 如果已经很生气，或者是中度敏感词
    if (companionMood < 20 || result.sensitivity_level === "medium") {
      // 设置为生气状态
      setIsAngry(true);
      
      try {
        setIsLoadingEmoji(true);
        // 使用默认生气表情
        setAngerEmoji("https://imgs.aixiaocai.com/assets/xiaoyou/angry_emoji.png");
      } catch (error) {
        console.error("获取生气表情失败", error);
      } finally {
        setIsLoadingEmoji(false);
      }
      
      // 设置生气文本
      if (result.sensitivity_level === "medium") {
        setAngerMessage("你的话让小悠很不舒服，请不要这样说话...");
      } else {
        setAngerMessage("小悠现在很生气，不想和你说话了...");
      }
      
      // 设置计时器，5秒后恢复
      if (angerTimer) clearTimeout(angerTimer);
      const timer = setTimeout(() => {
        setIsAngry(false);
        // 如果是中度敏感，且心情值过低，可能需要退出对话
        if (result.sensitivity_level === "medium" && companionMood < 10) {
          setShouldExit(true);
        }
      }, 5000);
      setAngerTimer(timer);
      
      setLoading(false);
      return;
    }
    
    // 如果是低度敏感词，发送提醒消息
    const warningMessage: MessageType = {
      role: "companion",
      content:
        result.sensitivity_level === "medium" || result.sensitivity_level === "low"
        ? "请不要说这样的话，这让我很不舒服..." 
        : "我不太喜欢你说的话，能换个话题吗？",
    };
    
    setMessages((prev) => [...prev, warningMessage]);
    setLoading(false);
  };

  // 处理按键事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  // 处理选择表情
  const handleEmojiSelect = (emoji: string) => {
    setInput((prev) => prev + emoji);
    setShowEmojiPicker(false);
    inputRef.current?.focus();
  };

  // 处理选择图片
  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (typeof event.target?.result === "string") {
          setSelectedImage(event.target.result);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理发送图片
  const handleSendImage = () => {
    if (!selectedImage || loading) return;

    const imageMessage: MessageType = {
      role: "user",
      content: `[图片]`,
      imageUrl: selectedImage,
    };

    setMessages((prev) => [...prev, imageMessage]);
    setSelectedImage(null);
    setLoading(true);

    // 模拟AI回复图片消息
    setTimeout(() => {
      const replyOptions = [
        "这张图片真漂亮！谢谢你分享给我~",
        "看起来很有趣呢！我很喜欢这张图片",
        "这张照片拍得真好，你有很好的审美眼光！",
        "哇，真是一张很棒的图片！",
      ];
      
      const companionMessage: MessageType = {
        role: "companion",
        content: replyOptions[Math.floor(Math.random() * replyOptions.length)],
      };
      
      setMessages((prev) => [...prev, companionMessage]);
      setLoading(false);
      
      // 滚动到底部
      setTimeout(() => {
        chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
      }, 100);
    }, 1500);
  };

  // 清除选择的图片
  const handleClearImage = () => {
    setSelectedImage(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };
  
  // 处理取消选择表情
  const handleCloseEmojiPicker = () => {
    setShowEmojiPicker(false);
  };

  // 添加点击外部关闭菜单的处理函数
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (showEmojiPicker || showQuickActions) {
        const target = event.target as HTMLElement;
        if (
          !target.closest(".emoji-picker") &&
          !target.closest(".tool-button") &&
          !target.closest(".quick-actions-menu") &&
          !target.closest(".quick-action-button")
        ) {
          setShowEmojiPicker(false);
          setShowQuickActions(false);
        }
      }
    };

    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [showEmojiPicker, showQuickActions]);

  // 组件卸载时清理计时器
  useEffect(() => {
    return () => {
      if (angerTimer) {
        clearTimeout(angerTimer);
      }
      if (exitTimer) {
        clearTimeout(exitTimer);
      }
    };
  }, [angerTimer, exitTimer]);

  // 处理图片点击预览
  const handleImageClick = (imageUrl: string) => {
    setPreviewImage(imageUrl);
    setShowImagePreview(true);
  };

  // 关闭图片预览
  const handleClosePreview = () => {
    setShowImagePreview(false);
    setPreviewImage(null);
  };

  // profile 未就绪时不渲染聊天
  if (!profileReady) {
    return (
      <div className="loading-container">
        <Spin size="large" tip="正在初始化虚拟恋人..." />
      </div>
    );
  }

  // 修改聊天头部
  const renderHeader = () => {
    return (
      <div className="chat-header" style={chatHeaderStyle}>
        <div className="chat-header-left">
          <ArrowLeftOutlined onClick={handleBack} className="back-button" />
          <span className="chat-title">你的恋人-小悠</span>
        </div>

        <div className="chat-header-right">
          <span style={intimacyStyle}>亲密度: {intimacy}%</span>
        </div>
      </div>
    );
  };

  // 修改聊天UI，添加顶部头像和心情值展示
  const renderChatHeader = () => {
    return (
      <div className="chat-subheader" style={chatSubheaderStyle}>
        <div className="subheader-left">
          <Avatar
            src={companionAvatar}
            size={40}
            onClick={handleAvatarClick}
            className="clickable-avatar companion-header-avatar"
          />
          <div className="subheader-info">
            <div className="subheader-name">小悠</div>
            <div className="subheader-style">
              <StyleDropdown
                value={styleType}
                options={STYLE_TYPES}
                onChange={handleStyleChange}
              />
            </div>
          </div>
        </div>

        <div className="mood-indicator">
          <span style={moodIndicatorStyle}>心情: {companionMood}%</span>
        </div>
      </div>
    );
  };

  // 修改按钮样式
  const renderSendButton = () => (
    <button
      type="button"
      disabled={loading}
      onClick={handleSend}
      className="send-button"
      style={{
        ...sendButtonStyle,
        opacity: loading ? 0.6 : 1,
        cursor: loading ? "not-allowed" : "pointer",
      }}
      aria-label="发送消息"
      title="发送消息"
    >
      <SendOutlined />
    </button>
  );

  // 消息渲染逻辑中增加对imageUrl的支持
  const renderMessage = (message: MessageType, index: number) => {
    const isUser = message.role === "user";
    
    // 处理可能的JSON字符串内容
    let content = message.content;
    if (!isUser && content && typeof content === 'string') {
      // 检查是否是JSON格式
      if (content.trim().startsWith('{') && content.trim().endsWith('}')) {
        try {
          const parsed = JSON.parse(content);
          // 尝试从多个可能的字段中提取文本
          if (parsed.answer && typeof parsed.answer === 'string') {
            content = parsed.answer;
          } else if (parsed.text && typeof parsed.text === 'string') {
            content = parsed.text;
          } else if (parsed.content && typeof parsed.content === 'string') {
            content = parsed.content;
          } else if (parsed.response && typeof parsed.response === 'string') {
            content = parsed.response;
          } else if (parsed.message && typeof parsed.message === 'string') {
            content = parsed.message;
          }
        } catch (e) {
          // 解析失败，保持原样
          console.log('JSON解析失败，使用原始文本');
        }
      }
    }
    
    return (
      <div
        key={index}
        className={`chat-message ${
          isUser ? "user-message" : "companion-message"
        }`}
      >
        <div className="avatar">
          <Avatar
            src={isUser ? userAvatar : companionAvatar}
            size={40}
            style={{ cursor: isUser ? "default" : "pointer" }}
            onClick={!isUser ? handleAvatarClick : undefined}
          />
        </div>
        <div className="message-content" style={isUser ? userMessageStyle : companionMessageStyle}>
          {content.split("\n").map((text, i) => (
            <p key={i} style={{ margin: "0 0 6px 0", padding: 0 }}>
              {text}
            </p>
          ))}
          {message.imageUrl && (
            <div className="message-image">
              <img 
                src={message.imageUrl} 
                alt="生成的图片" 
                style={{
                  maxWidth: "100%",
                  borderRadius: "8px",
                  marginTop: "8px",
                  cursor: "pointer",
                }}
                onClick={() => handleImageClick(message.imageUrl!)}
              />
            </div>
          )}
        </div>
      </div>
    );
  };

  // 更新handleGetOutfit函数
  const handleGetOutfit = async () => {
    // 防止重复调用
    if (outfitLoading || generatingImage) {
      console.log("已经在生成穿搭图片，请稍候...");
      return;
    }
  };
  
  // 添加聊天背景样式
  const chatContainerStyle: React.CSSProperties = {
    background: '#fff',
    minHeight: '100vh',
    display: 'flex',
    flexDirection: 'column',
  };

  // 添加聊天头部样式
  const chatHeaderStyle: React.CSSProperties = {
    background: 'linear-gradient(to right, #ff7eb3, #ff5b99)',
    color: 'white',
    boxShadow: '0 2px 8px rgba(255, 138, 180, 0.5)',
  };

  // 添加聊天子头部样式
  const chatSubheaderStyle: React.CSSProperties = {
    background: '#fff',
    borderBottom: '1px solid rgba(255, 192, 203, 0.3)',
  };

  // 添加用户消息气泡样式
  const userMessageStyle: React.CSSProperties = {
    backgroundColor: '#ff8ab4',
    color: 'white',
    borderRadius: '18px 18px 0 18px',
    boxShadow: '0 2px 4px rgba(255, 138, 180, 0.3)',
  };

  // 添加伴侣消息气泡样式
  const companionMessageStyle: React.CSSProperties = {
    backgroundColor: 'white',
    borderRadius: '18px 18px 18px 0',
    boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
    border: '1px solid rgba(255, 192, 203, 0.3)',
  };

  // 添加输入框样式
  const inputContainerStyle: React.CSSProperties = {
    backgroundColor: 'white',
    borderTop: '1px solid rgba(255, 192, 203, 0.5)',
  };

  // 添加心情指示器样式
  const moodIndicatorStyle: React.CSSProperties = {
    background: 'linear-gradient(to right, #ffcce6, #ff8ab4)',
    color: 'white',
    padding: '4px 12px',
    borderRadius: '15px',
    fontSize: '12px',
    fontWeight: 'bold',
    boxShadow: '0 2px 4px rgba(255, 138, 180, 0.3)',
  };

  // 添加输入框内部样式
  const inputStyle: React.CSSProperties = {
    border: 'none',
    borderRadius: '20px',
    padding: '10px 15px',
    flex: 1,
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    boxShadow: 'inset 0 1px 3px rgba(255, 138, 180, 0.2)',
    fontSize: '14px',
    color: '#333',
    outline: 'none',
    transition: 'all 0.3s ease',
  };
  
  // 添加发送按钮样式
  const sendButtonStyle: React.CSSProperties = {
    background: 'linear-gradient(to right, #ff7eb3, #ff5b99)',
    color: 'white',
    border: 'none',
    borderRadius: '50%',
    width: '40px',
    height: '40px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    boxShadow: '0 2px 6px rgba(255, 138, 180, 0.4)',
    transition: 'all 0.3s ease',
  };

  // 添加亲密度样式
  const intimacyStyle: React.CSSProperties = {
    background: 'linear-gradient(to right, #ff9fcf, #ff7eb3)',
    color: 'white',
    padding: '4px 12px',
    borderRadius: '15px',
    fontSize: '12px',
    fontWeight: 'bold',
    boxShadow: '0 2px 4px rgba(255, 138, 180, 0.3)',
    marginLeft: '10px',
  };

  return (
    <div className="chat-container" style={chatContainerStyle}>
      {renderHeader()}

      {showProfile && (
        <CompanionProfile
          onClose={() => setShowProfile(false)}
          styleType={styleType}
          isModal={true}
          companionAvatar={companionAvatar}
          onStyleChange={handleStyleChange}
        />
      )}
      
      {renderChatHeader()}

      {/* 聊天消息区域 */}
      <div ref={messageListRef} className="message-list">
        {/* 消息气泡 */}
        {messages.map((message, index) => renderMessage(message, index))}

        <div ref={chatEndRef} />
      </div>

      {/* 图片预览弹窗 */}
      {showImagePreview && previewImage && (
        <div className="image-preview-overlay" onClick={handleClosePreview}>
          <div
            className="image-preview-container-fullscreen"
            onClick={(e) => e.stopPropagation()}
          >
            <img
              src={previewImage}
              alt="预览图片"
              className="image-preview-fullscreen"
            />
            <button
              onClick={handleClosePreview}
              className="close-preview-button"
            >
              关闭
            </button>
          </div>
        </div>
      )}

      {/* 选择的图片预览 */}
      {selectedImage && (
        <div className="image-preview-container">
          <img src={selectedImage} alt="预览" className="image-preview" />
          <div className="image-preview-actions">
            <Button type="primary" onClick={handleSendImage} disabled={loading}>
              发送
            </Button>
            <Button onClick={handleClearImage}>取消</Button>
          </div>
        </div>
      )}

      {/* 输入框区域 */}
      <div className="input-container" style={inputContainerStyle}>
        <div className="input-area-wrapper">
          {/* 表情按钮 */}
            <div 
              className="tool-button"
              onClick={() => setShowEmojiPicker(!showEmojiPicker)}
            >
              <SmileOutlined className="tool-icon" />
            </div>

          {/* 图片按钮 */}
            <div className="tool-button">
              <label htmlFor="image-upload" className="tool-label">
              <PictureOutlined className="tool-icon" />
              </label>
              <input
                id="image-upload"
                type="file"
                ref={fileInputRef}
                className="image-upload-button"
                accept="image/*"
                onChange={handleImageSelect}
                aria-label="上传图片"
                title="选择要上传的图片"
              />
          </div>

          {/* 输入框 */}
          <div className="chat-input-container">
          <input
            ref={inputRef}
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
              placeholder="说点甜言蜜语..."
            className="chat-input"
            disabled={loading || isAngry}
            style={inputStyle}
          />
          </div>

          {/* 发送按钮 */}
          <button
            type="button"
            onClick={handleSend}
            className="send-button"
            style={sendButtonStyle}
            aria-label="发送消息"
            title="发送消息"
          >
            <SendOutlined />
          </button>
        </div>
      </div>

      {/* 表情选择器 */}
      {showEmojiPicker && (
        <div className="emoji-picker">
          <div className="emoji-picker-header">
            <span>常用表情</span>
            <span className="emoji-close" onClick={handleCloseEmojiPicker}>
              ×
            </span>
          </div>
          <div className="emoji-list">
            {commonEmojis.map((emoji, index) => (
              <span 
                key={index} 
                className="emoji-item" 
                onClick={() => handleEmojiSelect(emoji)}
              >
                {emoji}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 快捷操作菜单 */}

      {/* 生气状态显示 */}
      {isAngry && (
        <div className="anger-overlay">
          {isLoadingEmoji ? (
            <Spin size="large" />
          ) : (
            <>
              <img src={angerEmoji} alt="Angry" className="anger-emoji" />
              <div className="anger-message">{angerMessage}</div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default ChatBot;

<style jsx>{`
  .profile-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .profile-modal-content {
    background-color: transparent;
    z-index: 1001;
  }
`}</style>
